package com.twb.wechat.service.impl;

import com.twb.system.entity.twbTenantConfig.dto.TenantConfigWxCpAppDto;
import com.twb.system.entity.twbTenantConfig.dto.TenantConfigWxCpDto;
import com.twb.system.service.ITwbTenantConfigService;
import com.twb.wechat.cp.config.WxCpConfiguration;
import com.twb.wechat.service.ITwbWxCpService;
import java.util.HashMap;
import java.util.Map;
import lombok.val;
import me.chanjar.weixin.cp.api.WxCpService;
import me.chanjar.weixin.cp.api.impl.WxCpServiceImpl;
import me.chanjar.weixin.cp.config.impl.WxCpDefaultConfigImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author DHL
 * @ClassName: WxCpService
 * @Description:
 * @date 2023/1/30、10:38
 */
@Service("twbWxCpService")
public class TwbWxCpService implements ITwbWxCpService {

    private static Map<String, WxCpService> cpServices = new HashMap<>();

    @Autowired
    ITwbTenantConfigService twbTenantConfigService;
    @Override
    public WxCpService getWxCpService(Integer agentId, String domain) {
        String key = String.format("%s_%s", domain.replace(".", ""), agentId);

        WxCpService wxCpService = cpServices.get(key);
        if(wxCpService != null){
            return wxCpService;
        }

        TenantConfigWxCpDto wxCpConfig = twbTenantConfigService.getWxCpConfig(domain);
        TenantConfigWxCpAppDto wxCpAppConfig = null;

        for (TenantConfigWxCpAppDto appConfig : wxCpConfig.getAppConfigs()) {
            if(appConfig.getAgentId().equals(agentId.toString())){
                wxCpAppConfig = appConfig;
            }
        }

        if(wxCpAppConfig == null){
            return null;
        }

        val configStorage = new WxCpDefaultConfigImpl();
        configStorage.setCorpId(wxCpConfig.getCorpId());
        configStorage.setAgentId(Integer.valueOf(wxCpAppConfig.getAgentId()));
        configStorage.setCorpSecret(wxCpAppConfig.getSecret());
        configStorage.setToken(wxCpAppConfig.getToken());
        configStorage.setAesKey(wxCpAppConfig.getAesKey());
        configStorage.setOauth2redirectUri(wxCpAppConfig.getOauth2redirectUri());
        val service = new WxCpServiceImpl();
        service.setWxCpConfigStorage(configStorage);

        cpServices.put(key, service);

        return service;
    }
}
